<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Friend_add extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
    public function __construct()
    {
		session_start();
		parent::__construct();
		$this->load->model('friendtop_model');
	}
	public function index()
	{
		//$temp=$this->session->userdata('access_token');
		$temp=$_SESSION['token']['access_token'];
        if ( empty($temp))   //如果用户没登录
        {
            $o = new SaeTOAuthV2(WB_AKEY, WB_SKEY);
            $code_url = $o->getAuthorizeURL(WB_CALLBACK_URL);
            echo "<meta http-equiv=refresh content='0; url=$code_url'>";  //跳转到授权页面
        }
        else
		{
			$f_name=$this->input->post("value");	//从AJAX请求中获取参数“fuid”
			//var_dump($f_name);
			$count_today=0;		//今天的微博更新数量
			$code='';	//ajax请求返回值的提示代号
			$msg='';	//ajax请求返回之的提示信息
			$result='';	//ajax请求的返回值内容
			
			$c = new SaeTClientV2( WB_AKEY , WB_SKEY ,$temp );
			$f_info=$c->show_user_by_name($f_name);	//通过用户昵称获取用户信息
			if( ! empty($f_info))
			{
				$fuid=$f_info['id'];	//对应用户的UID				
				$uid_get=$c->get_uid();
				$uid=$uid_get['uid'];	//获取当前登录用户的UID
				$fuids=$c->friends_ids_by_id($uid,0,1000);	//该用户关注的UID信息，取1000条
				$fids=(array)$fuids['ids'];	//当前登录用户的关注对象的UID列表
				//var_dump($fids); 

			
			
				/*1、首先检查该UID是否在当前登录用户的关注列表里
				 *		如果不在关注列表里面，则提示用户没有关注：$code='0'
				 *2、如果已经关注该用户，第二步检查该UID是否已经存在与wb_appFriendsView_custom 表中的fids字段
				 *		如果已经存在于数据库中，则提示用户已经添加该UID:$code='1'
				 *3、如果既是当前登录用户的关注对象，又没存在于数据库中，则向数据表wb_appFriendsView_custom 的fids字段添加该UID，并向
				 *   数据表wb_user中添加该UID用户的详细信息，并向前端返回其用户信息：$code='2'
				 */

				if(in_array($fuid,$fids))	//如果该UID是当前登录用户关注的对象
				{
					//echo "已经关注";
					//var_dump($fuid);
					$sql_fids="select fids from wb_appFriendsView_custom  where uid=$uid";
					$fids_db=$this->db->query($sql_fids);
					$fids_db=$fids_db->result_array();
					//var_dump($fids_db);
					
					$fids_db_arr=explode("-",$fids_db[0]['fids']);
					//var_dump($fids_db_arr);

					//检查该UID是否已存在于数据库中
					if(in_array($fuid,$fids_db_arr))	//如果该UID已经存在于数据库中
					{
						//echo "在数据库中";
						$code=1;
						$msg="该用户已经被添加";
					}
					else	//是关注对象，并且未曾添加过
					{
						//echo "不在数据库中";
						$fuid=1+$fuid-1;	//将string类型的fuid转化为数字类型
						$today=date("d");	//今天的日期（天）
						$weibo=$c->user_timeline_by_id($fuid,1,100);	//取出100条最新微博
						
						//计算今天微博的更新数量
						do
						{
							$creat_time=strtotime($weibo['statuses'][$count_today]['created_at']);	//本条微博发布的时间（天）
							$count_today++;
						}while(date("d",$creat_time) == $today);
						
						//重置session
						if(isset($_SESSION['weibos']))
							array_push($_SESSION['weibos'],array("$fuid"=>$weibo));
						
						$friend_info=$c->show_user_by_id($fuid);	//调用API获取该关注对象的用户信息
						$img_url=$friend_info['avatar_large'];
						$title=$friend_info['screen_name'];
						if($count_today == 0)
						{
							$result="<li id='$fuid'><a class='membericon'  ><img title='$title' src='$img_url' /></a></li>";
						}
						else
						{
							$result="<li id='$fuid'><a class='membericon'  ><img title='$title' src='$img_url' /><div class='msgimg'><span>$count_today</span></div></a></li>";
						}
						
						//向数据表wb_appFriendsView_custom 的fids字段添加该用户的UID
						$fids_new=$fids_db[0]['fids'].'-'.(string)$fuid;	//新的fids
						//var_dump($fids_new);
						$sql_update="UPDATE wb_appFriendsView_custom  SET fids='$fids_new' WHERE uid=$uid";
						$this->db->query($sql_update);

						//向数据表 wb_user中添加该UID的信息
						$this->friendtop_model->set_wb_user($friend_info['id'],$friend_info['screen_name'],$friend_info['gender'],$friend_info['profile_image_url'],$friend_info['avatar_large'],$friend_info['followers_count'],$friend_info['friends_count'],$friend_info['statuses_count'],$friend_info['favourites_count'],$friend_info['verified'],$friend_info['province'],$friend_info['city'],$friend_info['location'],$friend_info['description'],$friend_info['bi_followers_count'],$friend_info['domain'],$friend_info['created_at']);

						$code=2;
						$msg='添加成功！';
					}
				}
				else
				{
					$code=0;
					$msg='未关注此用户';
				}
			}

			$response=array
				(
					'count'=>$count_today,
					'code'=>$code,
					'msg'=>$msg,
					'result'=>$result
				);

			echo json_encode($response);
        }
	}	
}
